<?php
namespace app\api\controller\order;

// 底层控制器
use think\Controller;

//引入cookie
use think\Cookie;

class Order extends Controller {
    // 构造函数

    public function __construct() {
        // 手动把父类的方法获取过来
        parent::__construct();

        $this->UserModel = model( 'User.User' );
        $this->CartModel = model( 'Cart' );
        $this->ProductModel = model( 'Product.Product' );
        $this->VipModel = model( 'Product.Vip' );
        $this->AddressModel = model( 'User.Address' );
        $this->OrderModel = model( 'Order.Order' );
        $this->OrderProductModel = model( 'Order.Product' );
        $this->RecordModel = model( 'User.Record' );
    }

    // 添加订单

    public function add() {
        if ( $this->request->isPost() ) {
            $userid = $this->request->param( 'userid', 0 );
            $addrid = $this->request->param( 'addrid', 0 );
            $cartids = $this->request->param( 'cartids', 0 );
            $content = $this->request->param( 'content', 0 );

            // 获取用户信息
            $userinfo = $this->UserModel->find( $userid );

            // 当没有找到用户
            if ( !$userinfo ) {
                $this->error( '用户不存在，请登录' );
                exit;
            }

            // 查找这个人的地址
            $address = $this->AddressModel->where( [ 'userid' => $userid, 'id' => $addrid ] )->find();

            if ( !$address ) {
                $this->error( '收货地址不存在' );
                exit;
            }

            $where = [
                'cart.id' => [ 'in', $cartids ],
                'userid' => $userid,
            ];

            // 查询购物车产品数据
            $cartlist = $this->CartModel->with( 'product' )->where( $where )->select();

            if ( !$cartlist ) {
                $this->error( '下单商品数据为空，请重新选择商品！' );
                exit;
            }

            // 判断商品库存是否充足
            foreach ( $cartlist as $item ) {
                // 购物车商品的数量
                $nums = $item[ 'nums' ];
                // 商品的库存
                $stock = $item[ 'product' ][ 'stock' ];

                // 让 商品的库存数量 - 购物车商品的数量 基准计算bcsub
                $pronums = bcsub( $stock, $nums );

                if ( $pronums < 0 ) {
                    // 判断库存是否正确
                    $this->error( $item[ 'product' ][ 'name' ].'库存不足，请重新选择！' );
                    exit;
                }
            }

            // 查询用户的积分是否满足下单
            $sumtotal = [
                'id' => [ 'in', $cartids ],
                'userid' => $userid,
            ];

            // 查询下单需要的总价格( 积分 )
            $total = $this->CartModel->where( $sumtotal )->sum( 'total' );

            // 用户的积分
            $point = $userinfo[ 'point' ];

            // 判断用户积分够不够
            $UpdatePoint = bcsub( $point, $total );

            if ( $UpdatePoint < 0 ) {
                $this->error( '积分不足，请充值后操作！' );
                exit;
            }

            // 开启事务
            // 订单表（INSERT ) 订单商品表( INSERT ) 商品库存( UPDATE ) 用户积分( UPDATE ) 消费记录( INSERT ) 购物车( DELETE )

            $this->OrderModel->startTrans();
            $this->OrderProductModel->startTrans();
            $this->ProductModel->startTrans();
            $this->UserModel->startTrans();
            $this->RecordModel->startTrans();
            $this->CartModel->startTrans();

            /* 订单表（INSERT ) */
            // 组转订单表数据
            $OrderData = [
                'userid' => $userid,
                'addrid' => $addrid,
                'code' => build_code( 'AK' ),
                'content' => $content,
                'status' => 1,
                'total' => $total,
            ];

            // 订单表插入
            $OrderStatus = $this->OrderModel->validate( 'common/Order/Order' )->save( $OrderData );

            if ( $OrderStatus === false ) {
                $this->error( $this->OrderModel->getError() );
                exit;
            }

            /* 订单商品表( INSERT ) */
            // 订单商品表插入
            $OrderProductData = [];
            $ProductData = [];

            foreach ( $cartlist as $item ) {
                // 订单商品
                $OrderProductData[] = [
                    'orderid' => $this->OrderModel->id,
                    'proid' => $item[ 'proid' ],
                    'nums' => $item[ 'nums' ],
                    'price' => $item[ 'price' ],
                    'total' => $item[ 'total' ],
                ];

                // 商品库存 - 购物车数量
                $stock = bcsub( $item[ 'product' ][ 'stock' ], $item[ 'nums' ] );

                // 商品库存
                $ProductData[] = [
                    'id' => $item[ 'proid' ],
                    'stock' => $stock,
                ];
            }

            // 插入订单商品表
            $OrderProductStatus = $this->OrderProductModel->validate( 'common/Order/Product' )->saveAll( $OrderProductData );

            if ( $OrderProductStatus === false ) {
                // 回滚
                $this->OrderModel->rollback();
                $this->error( $this->OrderProductModel->getError() );
                exit;
            }

            /* 商品表更新( UPDATE ) */
            $ProductStatus = $this->ProductModel->isUpdate()->saveAll( $ProductData );

            if ( $ProductStatus === false ) {
                // 回滚
                $this->OrderModel->rollback();
                $this->OrderProductModel->rollback();
                $this->error( $this->ProductModel->getError() );
                exit;
            }

            /* 用户积分更新( UPDATE ) */
            $UserStatus = $this->UserModel->isUpdate()->save( [ 'id' => $userid, 'point' => $UpdatePoint ] );

            if ( $UserStatus === false ) {
                // 回滚
                $this->OrderModel->rollback();
                $this->OrderProductModel->rollback();
                $this->ProductModel->rollback();
                $this->error( $this->UserModel->getError() );
                exit;
            }

            /* 消费记录( INSERT ) */
            // 插入消费记录
            $RecordData = [
                'point' => $total,
                'content' => '订单号：'.$OrderData[ 'code' ]."---消费的积分为：$total",
                'state' => 5,
                'userid' => $userid,
            ];

            // 插入消费积分记录表
            $RecordStatus = $this->RecordModel->validate( 'common/User/Record' )->save( $RecordData );

            if ( $RecordStatus === false ) {
                // 回滚
                $this->OrderModel->rollback();
                $this->OrderProductModel->rollback();
                $this->ProductModel->rollback();
                $this->UserModel->rollback();
                $this->error( $this->RecordModel->getError() );
                exit;
            }

            /* 购物车( DELETE ) */
            // 购物车删除商品
            $CartStatus = $this->CartModel->destroy( $cartids );

            if ( $CartStatus === false ) {
                // 回滚
                $this->OrderModel->rollback();
                $this->OrderProductModel->rollback();
                $this->ProductModel->rollback();
                $this->UserModel->rollback();
                $this->RecordModel->rollback();
                $this->error( $this->CartModel->getError() );
                exit;
            }

            if ( $OrderStatus !== false && $OrderProductStatus !== false && $ProductStatus !== false && $UserStatus !== false && $RecordStatus !== false && $CartStatus !== false ) {
                // 提交事务
                $this->OrderModel->commit();
                $this->OrderProductModel->commit();
                $this->ProductModel->commit();
                $this->UserModel->commit();
                $this->RecordModel->commit();
                $this->CartModel->commit();

                $this->success( '下单成功，等待商家发货！', '/user/order/index' );
                exit;
            } else {
                // 回滚
                $this->OrderModel->rollback();
                $this->OrderProductModel->rollback();
                $this->ProductModel->rollback();
                $this->UserModel->rollback();
                $this->RecordModel->rollback();
                $this->CartModel->rollback();
                $this->error( '下单失败，请冲洗操作！' );
                exit;
            }
        }
    }

    // 添加一个商品订单

    public function oneadd() {
        if ( $this->request->isPost() ) {
            $userid = $this->request->param( 'userid', 0 );
            $addrid = $this->request->param( 'addrid', 0 );
            $proid = $this->request->param( 'proid', 0 );
            $content = $this->request->param( 'content', 0 );

            // 获取用户信息
            $userinfo = $this->UserModel->find( $userid );

            // 当没有找到用户
            if ( !$userinfo ) {
                $this->error( '用户不存在，请登录' );
                exit;
            }

            // 查找这个人的地址
            $address = $this->AddressModel->where( [ 'userid' => $userid, 'id' => $addrid ] )->find();

            if ( !$address ) {
                $this->error( '收货地址不存在' );
                exit;
            }

            $productinfo = $this->ProductModel->where( [ 'id' => $proid ] )->find();

            $total = $productinfo[ 'price' ];

            // 用户的积分
            $point = $userinfo[ 'point' ];

            // 判断用户积分够不够
            $UpdatePoint = bcsub( $point, $total );

            if ( $UpdatePoint < 0 ) {
                $this->error( '积分不足，请充值后操作！' );
                exit;
            }

            // 开启事务
            // 订单表（INSERT ) 订单商品表( INSERT ) 商品库存( UPDATE ) 用户积分( UPDATE ) 消费记录( INSERT ) 购物车( DELETE )

            $this->OrderModel->startTrans();
            $this->OrderProductModel->startTrans();
            $this->ProductModel->startTrans();
            $this->UserModel->startTrans();
            $this->RecordModel->startTrans();

            /* 订单表（INSERT ) */
            // 组转订单表数据
            $OrderData = [
                'userid' => $userid,
                'addrid' => $addrid,
                'code' => build_code( 'AK' ),
                'content' => $content,
                'status' => 1,
                'total' => $total,
            ];

            // 订单表插入
            $OrderStatus = $this->OrderModel->validate( 'common/Order/Order' )->save( $OrderData );

            if ( $OrderStatus === false ) {
                $this->error( $this->OrderModel->getError() );
                exit;
            }

            /* 订单商品表( INSERT ) */
            // 订单商品表插入
            $OrderProductData = [];
            $ProductData = [];

            // 订单商品
            $OrderProductData = [
                'orderid' => $this->OrderModel->id,
                'proid' => $proid,
                'nums' => 1,
                'price' => $total,
                'total' => $total,
            ];

            // 商品库存 - 购物车数量
            $stock = bcsub( $productinfo[ 'stock' ], 1 );

            // 商品库存
            $ProductData = [
                'id' => $proid,
                'stock' => $stock,
            ];

            // 插入订单商品表
            $OrderProductStatus = $this->OrderProductModel->validate( 'common/Order/Product' )->save( $OrderProductData );

            if ( $OrderProductStatus === false ) {
                // 回滚
                $this->OrderModel->rollback();
                $this->error( $this->OrderProductModel->getError() );
                exit;
            }

            /* 商品表更新( UPDATE ) */
            $ProductStatus = $this->ProductModel->isUpdate()->save( $ProductData );

            if ( $ProductStatus === false ) {
                // 回滚
                $this->OrderModel->rollback();
                $this->OrderProductModel->rollback();
                $this->error( $this->ProductModel->getError() );
                exit;
            }

            /* 用户积分更新( UPDATE ) */
            $UserStatus = $this->UserModel->isUpdate()->save( [ 'id' => $userid, 'point' => $UpdatePoint ] );

            if ( $UserStatus === false ) {
                // 回滚
                $this->OrderModel->rollback();
                $this->OrderProductModel->rollback();
                $this->ProductModel->rollback();
                $this->error( $this->UserModel->getError() );
                exit;
            }

            /* 消费记录( INSERT ) */
            // 插入消费记录
            $RecordData = [
                'point' => $total,
                'content' => '订单号：'.$OrderData[ 'code' ]."---消费的积分为：$total",
                'state' => 5,
                'userid' => $userid,
            ];

            // 插入消费积分记录表
            $RecordStatus = $this->RecordModel->validate( 'common/User/Record' )->save( $RecordData );

            if ( $RecordStatus === false ) {
                // 回滚
                $this->OrderModel->rollback();
                $this->OrderProductModel->rollback();
                $this->ProductModel->rollback();
                $this->UserModel->rollback();
                $this->error( $this->RecordModel->getError() );
                exit;
            }

            if ( $OrderStatus !== false && $OrderProductStatus !== false && $ProductStatus !== false && $UserStatus !== false && $RecordStatus !== false ) {
                // 提交事务
                $this->OrderModel->commit();
                $this->OrderProductModel->commit();
                $this->ProductModel->commit();
                $this->UserModel->commit();
                $this->RecordModel->commit();

                $this->success( '下单成功，等待商家发货！', '/user/order/index' );
                exit;
            } else {
                // 回滚
                $this->OrderModel->rollback();
                $this->OrderProductModel->rollback();
                $this->ProductModel->rollback();
                $this->UserModel->rollback();
                $this->RecordModel->rollback();
                $this->error( '下单失败，请冲洗操作！' );
                exit;
            }
        }
    }

    // 订单列表

    public function list() {
        if ( $this->request->isPost() ) {
            $userid = $this->request->param( 'userid', 0 );
            $status = $this->request->param( 'status', 0 );

            // 获取用户信息
            $userinfo = $this->UserModel->find( $userid );

            // 当没有找到用户
            if ( !$userinfo ) {
                $this->error( '用户不存在，请登录' );
                exit;
            }

            // 设置条件
            $where = [];

            // 判断订单类型
            if ( $status != 0 ) {
                $where[ 'status' ] = $status;
            }

            $where[ 'userid' ] = $userid;

            // 查询订单信息
            $result = $this->OrderModel->where( $where )->select();

            if ( !$result ) {
                $this->success( '暂无订单数据！' );
                exit;
            }

            $orderlist = [];

            foreach ( $result as $item ) {

                // 组装订单数据
                $info = [
                    'id' => $item[ 'id' ],
                    'code' => $item[ 'code' ],
                    'total' => $item[ 'total' ],
                    'createtime' => $item[ 'createtime' ],
                    'status' => $item[ 'status' ],
                    'status_text' => $item[ 'status_text' ],
                ];

                // 通过订单的商品id查询商品表
                $product = $this->OrderProductModel->with( 'info' )->where( [ 'orderid' => $item[ 'id' ] ] )->find();

                // 判断订单中产品的结果，判断是否有这个商品
                if ( $product && $product[ 'info' ][ 'id' ] ) {
                    $info[ 'product' ] = $product[ 'info' ];
                }

                $orderlist[] = $info;
            }

            $this->success( '返回订单数据', null, $orderlist );
            exit;
        }
    }

    // 订单详情

    public function info() {
        if ( $this->request->isPost() ) {
            $userid = $this->request->param( 'userid', 0 );
            $id = $this->request->param( 'id', 0 );

            // 获取用户信息
            $userinfo = $this->UserModel->find( $userid );

            // 当没有找到用户
            if ( !$userinfo ) {
                $this->error( '用户不存在，请登录' );
                exit;
            }

            // 获取订单信息
            $orderinfo = $this->OrderModel->find( $id );

            if ( !$orderinfo ) {
                $this->error( '订单不存在，请去下单！' );
                exit;
            }

            // 获取商品信息
            $product = $this->OrderProductModel->with( 'info' )->where( [ 'orderid' => $id ] )->select();

            // 判断订单商品是否存在
            if ( !$product ) {
                $this->error( '订单商品不存在，请去下单！' );
                exit;
            }

            // 获取订单的收货地址
            $address = $this->AddressModel->with( [ 'provinces', 'citys', 'districts' ] )->find( $orderinfo[ 'addrid' ] );

            // 判断订单地址是否存在
            if ( !$address ) {
                $this->error( '订单地址不存在，请去下单！' );
                exit;
            }

            $data = [
                'order' => $orderinfo,
                'product' => $product,
                'address' => $address
            ];

            $this->success( '返回订单数据成功！', null, $data );
            exit;
        }
    }
}
?>